package com.ggs.interceptors;

import com.ggs.utils.JwtUtils;
import com.ggs.utils.ThreadLocalUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptors implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 处理OPTIONS预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        // 获取Token（兼容大小写）
        String token = request.getHeader("Authorization");
        if (token == null) {
            token = request.getHeader("authorization");
        }



//        // 浏览器获取到的token
//        String token = request.getHeader("Authorization");
        System.out.println("----!!!!=------"+token);
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if (redisToken == null)
                throw new RuntimeException();
            Map<String, Object> claims = JwtUtils.parseToken(token);
            // 将信息存在ThreadLocal中
            ThreadLocalUtils.set(claims);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            System.out.println("+++++++++++++++出错了+++++++++++++++++");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空，防止内存泄露
        ThreadLocalUtils.remove();
    }
}
